#include "SerialPortWorker.h"

#include <qdebug.h>
#include <qthread.h>

SerialPortWorker::SerialPortWorker(QObject* parent)
    : QObject(parent)
{

}

SerialPortWorker::~SerialPortWorker()
{
    if (m_serialPort->isOpen()) {
        m_serialPort->clear();
        m_serialPort->flush();
        m_serialPort->close();
        m_serialPort->deleteLater();
    }

    delete m_serialPort;
    m_serialPort = nullptr;
}

void SerialPortWorker::serialPortNameChanged(const QString& text)
{
    if (text.isEmpty() || text == m_serialPort->portName())
        return;

    if (m_serialPort->isOpen()) {
        m_serialPort->clear();
        m_serialPort->flush();
        m_serialPort->close();
        emit stateChanged(false);
    }

    m_serialPort->setPortName(text);
}

void SerialPortWorker::serialInit()
{
    m_serialPort = new QSerialPort();

    m_serialPort->setBaudRate(QSerialPort::Baud115200);
    m_serialPort->setDataBits(QSerialPort::Data8);
    m_serialPort->setStopBits(QSerialPort::OneStop);
    m_serialPort->setParity(QSerialPort::NoParity);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);

    connect(m_serialPort, &QSerialPort::readyRead, this, &SerialPortWorker::serialReadWork);
}

void SerialPortWorker::serialOpen()
{
    if (nullptr == m_serialPort)
        return;

    if (m_serialPort->isOpen()) {
        emit stateChanged(true);
        return;
    }

    if (!m_serialPort->open(QIODevice::ReadWrite)) {
        qDebug() << "SerialPortWorker Open Error:" << m_serialPort->errorString();
        emit stateChanged(false);
        return;
    }

    m_serialPort->setReadBufferSize(512);
    emit stateChanged(true);
}

void SerialPortWorker::serialClose()
{
    if (!m_serialPort->isOpen())
        return;

    m_serialPort->clear();
    m_serialPort->flush();
    m_serialPort->close();

    emit stateChanged(false);
}

void SerialPortWorker::serialReadWork()
{
    QByteArray data = m_serialPort->readAll();

    //qDebug() << "Rx:" << data;

    if (!data.isEmpty()) {
        emit handleReadRusult(data);
    }
}

void SerialPortWorker::serialWriteWork(const QByteArray& data)
{
    if (!m_serialPort->isOpen())
        return;

    QMutexLocker locker(&lock);

    m_serialPort->write(data);
}